/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * http://nodejs.cn/api/path.html#pathresolvepaths
 * 手动实现path.resolve部分功能 路径或路径片段的序列
 * @param path
 */
export function resolve(...path) {
  let paths = ''
  for (let i = (path.length - 1); i >= 0; i--) {
    // 有符号
    if (paths.replace(/^.*(\/)$/, '$1') === '/' || !paths) {
      paths = path[i] + paths
    } else {
      // 没有有符号
      paths = `${path[i]}/${paths}`
    }
    if (path[i].replace(/^(\/).*$/, '$1') === '/') {
      break
    }
  }
  return paths
}

/**
 * 查找子集在哪
 * @param data
 * @param val
 * @param parentArr
 * @param field
 * @returns {*[]|*}
 */
export function findSubset(data, val, parentArr = []) {
  data = JSON.parse(JSON.stringify(data))
  for (const key in data) {
    const current = data[key]
    if (current['meta']) {
      if (current['name'] === val) {
        current.path = resolve((parentArr.path || ''), current.path)
        parentArr.push(current)
        return false
      }
    }
    if (current.children) {
      const parent = findSubset(current.children, val, parentArr = [current ?? []])
      if (!parent) {
        break
      }
      parentArr.push(...parent)
    }
  }
  return parentArr.filter(val => val['meta'])
}